package com.dao;

import com.po.Comment;
import com.utils.JDBCUnits;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
    /**
     * 获取一个纸条的全部评论
     * @param note_id 纸条的编号
     * @return
     */
    public static List<Comment> getComment(int note_id){
        List<Comment> comments = new ArrayList<Comment>();

        Connection c = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            c = JDBCUnits.getConnectino();
            String sql = "select c.comment_content as content,t.name as name from note_comment c join t_usr t on t.id = c.user_id where c.note_id=? order by comment_time desc , user_id desc ";
            ps = c.prepareStatement(sql);
            ps.setInt(1,note_id);
            rs = ps.executeQuery();

            while(rs.next()){
                String content = rs.getString("content");
                String name = rs.getString("name");
                Comment comment = new Comment();
                comment.setContent(content);
                comment.setUser_name(name);

                comments.add(comment);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUnits.close(c,ps,rs);
        }

        return comments;
    }

    /**
     * 删除评论
     * @param note_id 纸条的id
     */
    public static void deleteComment(int note_id){
        Connection c = null;
        PreparedStatement ps = null;

        try {
            c = JDBCUnits.getConnectino();
            String sql = "delete from note_comment where note_id = ?";
            ps = c.prepareStatement(sql);
            ps.setInt(1,note_id);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUnits.close(c,ps);
        }
    }

    /**
     * 写评论
     * @param id    用户的id
     * @param note_id 纸条的id
     * @param comment_content 评论的内容
     * @return
     */
    public static int createComment(int id, int note_id ,String comment_content){
        int count = 0;
        Connection c = null;
        PreparedStatement ps = null;

        try {
            c = JDBCUnits.getConnectino();
            String sql ="insert into note_comment(note_id,user_id,comment_content,comment_time) values(?,?,?,now())";
            ps = c.prepareStatement(sql);
            ps.setInt(1,note_id);
            ps.setInt(2,id);
            ps.setString(3,comment_content);
            count = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUnits.close(c,ps);
        }

        return count;
    }
}
